package com.saifan.wyy_ov.ui.onlishop;
import java.util.ArrayList;
import java.util.List;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.data.bean.GroupBuyBean;
import com.saifan.wyy_ov.data.bean.PopCategoryBean;
import com.saifan.wyy_ov.data.bean.PopCategoryBean.Type;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.ui.view.RefreshLayout.OnLoadListener;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import lomasky.ma.xui.BaseRecyclerViewAdapter;
import lomasky.ma.xui.BaseViewHolder;
import lomasky.ma.xui.RecyclerViewAdapter;
import lomasky.ma.xui.WrapContentLineaLayoutManager;

public class PromotionActivity extends BaseActivity {
	// Content View Elements
	private Toolbar toolbar;
	private ListView list_group_buy;
	private TextView tv_title, tv_category;
	private RefreshLayout swipe;
	private AdapterPromotion adapterGroupBuy;
	private CommonDataBean requestBean;
	private GetData getData;
	private int pageCount = 10;// 页面数
	private int page = 0;// 第几页
	boolean hasMoreData = true;
	protected  List<GroupBuyBean> groupBuyBeans = new ArrayList<GroupBuyBean>();
	private PopCategoryBean popCategoryBean;
	private PopupWindow popupWindow;
	private List<PopCategoryBean> popList = new ArrayList<PopCategoryBean>();
    RecyclerViewAdapter<PopCategoryBean.Type> adapterRight;
    RecyclerViewAdapter<PopCategoryBean> adapterLeft;
	private int leftPosition = 0, rightPosition = -1;
	protected List<PopCategoryBean> dataList;
	protected String storeType;
	private RelativeLayout loadlay;
	// End Of Content View Elements



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int Type = getIntent().getIntExtra("Type", -1);
		setContentView();




		if (Type == 1) {
			tv_title.setText("周边团购");
		} else if (Type == 2) {
			tv_title.setText("店铺促销");
		}
		requestBean = new CommonDataBean();
		requestBean.setYXDID(getRoomInfoBean().getXMBS());

		requestBean.setType(Type);
		getData = new GetData();
		popList = new ArrayList<PopCategoryBean>();
		popCategoryBean = new PopCategoryBean();
		popCategoryBean.setSelectState(false);
		popCategoryBean.setTypeName("全部");
		popCategoryBean.setChildStoreType(new ArrayList<PopCategoryBean.Type>());
		popList.add(popCategoryBean);
		query();
		getStoreType();
	}
	public void query() {
		requestBean.setPage(page);
		swipe.setRefreshing(true);
		getData.getDataJson(this, Api.GroupBuy.SURROUNDGROUPBUY, requestBean, "", new ResponseData() {
			@Override
			public void onSuccess(String json) {
				// TODO Auto-generated method stub
				loadlay.setVisibility(View.GONE);
				swipe.setRefreshing(false);
				List<GroupBuyBean> list = new Gson().fromJson(json, new TypeToken<List<GroupBuyBean>>() {
				}.getType());
				if (list!=null&&!list.isEmpty()) {
					if (page ==0) {
						groupBuyBeans=list;
					}else {
						 groupBuyBeans.addAll(list);
					}
					page++;
					hasMoreData = true;
					
					
				} else {
					if (page ==0) {

						ToastUtil.showToast(PromotionActivity.this, "暂无更多促销信息");
					} 
					
					hasMoreData = false;
					if (page > 0) {
						page--;
					}  
					
				}
				adapterGroupBuy.setGroupBuyBeans(groupBuyBeans);
				adapterGroupBuy.notifyDataSetChanged();
			}
			@Override
			public void onFailed(String str) {
				// TODO Auto-generated method stub
				LogUtil.i(str);
				loadlay.setVisibility(View.GONE);
				hasMoreData = false;
				swipe.setRefreshing(false);
				ToastUtil.showToast(PromotionActivity.this, "暂无更多促销信息");
			}
		});
	}

	private void setContentView() {
		setContentView(R.layout.activity_promotion);
		loadlay = (RelativeLayout) findViewById(R.id.loading_lay);
		loadlay.setVisibility(View.VISIBLE);
		toolbar = (Toolbar) findViewById(R.id.toolbar);
		setSupportActionBar(toolbar);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		tv_category = (TextView) findViewById(R.id.tv_category);
		tv_title = (TextView) findViewById(R.id.title);
		list_group_buy = (ListView) findViewById(R.id.list_group_buy);
		swipe = (RefreshLayout) findViewById(R.id.swipe);
		swipe.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				page = 0;
				query();
			}
		});
		swipe.setOnLoadListener(new OnLoadListener() {
			@Override
			public void onLoad() {
				// TODO Auto-generated method stub
				if (hasMoreData) {
					query();
				}
			}
		});
		adapterGroupBuy = new AdapterPromotion(PromotionActivity.this, groupBuyBeans);
		list_group_buy.setAdapter(adapterGroupBuy);
	}
	// 选择店铺类别
	@SuppressWarnings("deprecation")
//	private void showSelectPop() {
//		String text = tv_category.getText().toString();
//		if (dataList != null && dataList.size() > 0) {
//			for (int i = 0; i < popList.size(); i++) {
//				for (int j = 0; j < popList.get(i).getChildStoreType().size(); j++) {
//					Type type = popList.get(i).getChildStoreType().get(j);
//					if (text.equals(type.getTypeName())) {
//						leftPosition = i;
//						type.setSelectState(true);
//						popList.get(i).setSelectState(true);
//					} else {
//						type.setSelectState(false);
//					}
//				}
//			}
//			if (text.equals("全部")) {
//				popList.get(0).setSelectState(true);
//				popList.get(0).setTypeName("全部");
//			}
//			View contentView = getLayoutInflater().inflate(R.layout.select_category_pop, null);
//			ListView leftListView = (ListView) contentView.findViewById(R.id.left_listview);
//			ListView rightListView = (ListView) contentView.findViewById(R.id.right_listview);
//			popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, DensityUtil.dip2px(PromotionActivity.this, 260), false);
//			adapterLeft = new CommonAdapter<PopCategoryBean>(PromotionActivity.this, popList, R.layout.select_pop_item_left) {
//				@Override
//				public void convert(ViewHolderHelper helper, PopCategoryBean item) {
//					LinearLayout layout = helper.getView(R.id.pop_item_left);
//					if (item.isSelectState()) {
//						layout.setBackgroundColor(getResources().getColor(R.color.list_item_onclick));
//					} else {
//						layout.setBackgroundColor(getResources().getColor(R.color.alpha));
//					}
//					helper.setText(R.id.name, item.getTypeName());
//				}
//			};
//			leftListView.setAdapter(adapterLeft);
//			leftListView.setOnItemClickListener(new OnItemClickListener() {
//				@Override
//				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//					if (rightPosition != -1 && leftPosition != 0) {
//						popList.get(leftPosition).getChildStoreType().get(rightPosition).setSelectState(false);
//					}
//					for (int i = 0; i < popList.size(); i++) {
//						if (i == arg2) {
//							popList.get(i).setSelectState(true);
//							leftPosition = i;
//						} else {
//							popList.get(i).setSelectState(false);
//						}
//					}
//					adapterLeft.mDatas = popList;
//					adapterLeft.notifyDataSetChanged();
//					adapterRight.mDatas = popList.get(leftPosition).getChildStoreType();
//					adapterRight.notifyDataSetChanged();
//					if (arg2 == 0) {
//						tv_category.setText("全部");
//						popupWindow.dismiss();
//						page = 0;
//						storeType = "全部";
//						requestBean.setStoreType(null);
//						groupBuyBeans.clear();
//						query();
//						return;
//					}
//				}
//			});
//			adapterRight = new CommonAdapter<Type>(PromotionActivity.this, popList.get(leftPosition).getChildStoreType(), R.layout.select_pop_item_right) {
//				@Override
//				public void convert(ViewHolderHelper helper, Type item) {
//					LinearLayout layout = helper.getView(R.id.pop_item_right);
//					if (item.isSelectState()) {
//						layout.setBackgroundColor(getResources().getColor(R.color.pop_right_onclick));
//					} else {
//						layout.setBackgroundColor(getResources().getColor(R.color.list_item_onclick));
//					}
//					helper.setText(R.id.name, item.getTypeName());
//				}
//			};
//			rightListView.setAdapter(adapterRight);
//			rightListView.setOnItemClickListener(new OnItemClickListener() {
//				@Override
//				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//					rightPosition = arg2;
//					adapterRight.mDatas = popList.get(leftPosition).getChildStoreType();
//					adapterRight.notifyDataSetChanged();
//					tv_category.setText(popList.get(leftPosition).getChildStoreType().get(arg2).getTypeName());
//					popupWindow.dismiss();
//					storeType = tv_category.getText().toString();
//					page = 0;
//					requestBean.setStoreType(storeType);
//                    query();
//				}
//			});
//			// 需要设置一下此参数，点击外边可消失
//			popupWindow.setBackgroundDrawable(new BitmapDrawable());
//			// 设置点击窗口外边窗口消失
//			popupWindow.setOutsideTouchable(true);
//			// 设置此参数获得焦点，否则无法点击
//			popupWindow.setFocusable(true);
//			popupWindow.showAsDropDown(toolbar);
//		} else {
//			getStoreType();
//			showSelectPop();
//		}
//	}

    private void showSelectPop() {
        String text = tv_category.getText().toString();
        if (dataList != null && dataList.size() > 0) {
            for (int i = 0; i < popList.size(); i++) {
                for (int j = 0; j < popList.get(i).getChildStoreType().size(); j++) {
                    Type type = popList.get(i).getChildStoreType().get(j);
                    if (text.equals(type.getTypeName())) {
                        leftPosition = i;
                        type.setSelectState(true);
                        popList.get(i).setSelectState(true);
                    } else {
                        type.setSelectState(false);
                    }
                }
            }
            if (text.equals("全部")) {
                popList.get(0).setSelectState(true);
                popList.get(0).setTypeName("全部");
            }
            View contentView = getLayoutInflater().inflate(R.layout.category_pop, null);
            RecyclerView leftListView = (RecyclerView) contentView.findViewById(R.id.left_listview);
            RecyclerView rightListView = (RecyclerView) contentView.findViewById(R.id.right_listview);
            leftListView.setLayoutManager(new WrapContentLineaLayoutManager(this));
            rightListView.setLayoutManager(new WrapContentLineaLayoutManager(this));

            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, false);
            adapterLeft = new RecyclerViewAdapter<PopCategoryBean>(PromotionActivity.this,  R.layout.list_category) {
                @Override
                public void onBind(BaseViewHolder holder, PopCategoryBean item, int p) {
                    CheckBox checkBox= holder.getCheckBox(R.id.checkbox);
                    checkBox.setChecked(item.isSelectState());
                    checkBox.setText(item.getTypeName());


                }
            };
            adapterLeft.setData(popList);
            leftListView.setAdapter(adapterLeft);
            adapterLeft.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int i) {
                    if (rightPosition != -1 && leftPosition != 0) {
                        popList.get(leftPosition).getChildStoreType().get(rightPosition).setSelectState(false);
                    }
                    for (int j = 0; j < popList.size(); j++) {
                        if (j == i) {
                            popList.get(j).setSelectState(true);
                            leftPosition = i;
                        } else {
                            popList.get(j).setSelectState(false);
                        }
                    }
                    adapterLeft.setData(popList);
                    adapterLeft.notifyDataSetChanged();
                    List<PopCategoryBean.Type> subList = popList.get(leftPosition).getChildStoreType();
                    adapterRight.setData(subList);

                    adapterRight.notifyDataSetChanged();
                    if (i == 0) {
                        tv_category.setText("全部");
                        popupWindow.dismiss();
                        page = 0;
                        storeType = "全部";
                        requestBean.setStoreType(null);
                        adapterGroupBuy.groupBuyBeans.clear();
                        query();
                        return;
                    }
                }
            });
            adapterRight = new RecyclerViewAdapter<PopCategoryBean.Type>(PromotionActivity.this, R.layout.list_type) {
                @Override
                public void onBind(BaseViewHolder baseViewHolder, PopCategoryBean.Type type, int i) {
                    baseViewHolder.setText(  R.id.checkbox, type.getTypeName());
                }


            };
            adapterRight.setData(popList.get(leftPosition).getChildStoreType());

            rightListView.setAdapter(adapterRight);
            adapterRight.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int i) {
                    rightPosition = i;
                    adapterRight.setData(popList.get(leftPosition).getChildStoreType());
                    adapterRight.notifyDataSetChanged();
                    tv_category.setText(popList.get(leftPosition).getChildStoreType().get(i).getTypeName());
                    popupWindow.dismiss();
                    storeType = tv_category.getText().toString();
                    page = 0;
                    requestBean.setStoreType(storeType);
                    adapterGroupBuy.getGroupBuyBeans().clear();
                    adapterGroupBuy.notifyDataSetChanged();
                    query();
                }
            });
            // 需要设置一下此参数，点击外边可消失
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            // 设置点击窗口外边窗口消失
            popupWindow.setOutsideTouchable(true);
            // 设置此参数获得焦点，否则无法点击
            popupWindow.setFocusable(true);
            popupWindow.showAsDropDown(toolbar);
        } else {
            getStoreType();
            showSelectPop();
        }
    }

	// 获取店铺类别
	private void getStoreType() {
		getData.httpGetDataJson(PromotionActivity.this, Api.StoreList.GETSTORETYPE, "", new ResponseData() {
			@Override
			public void onSuccess(String json) {
				dataList = (new Gson()).fromJson(json, new TypeToken<List<PopCategoryBean>>() {
				}.getType());
				popList.addAll(dataList);
			}
			@Override
			public void onFailed(String str) {
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.order_menu, menu);
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
        if (id == R.id.menu_more) {
            if (dataList != null && dataList.size() > 0) {
                showSelectPop();
            }

        } else {
        }
		return super.onOptionsItemSelected(item);
	}
}
